package org.spring.kun.common;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 上传图片工具类
 *
 */
public class UploadPicUtils {
    /**
     *
     * @param file 图片文件
     * @param request
     * @return 返回图片访问地址
     */
    public static String upload(MultipartFile file, HttpServletRequest request){
        // 生成唯一文件名
        String uuid = UUID.randomUUID().toString().trim();
        String filename = file.getOriginalFilename();
        String fileNames= uuid + filename;
        try {
            String basePath = request.getSession().getServletContext().getRealPath("/")+"/static";
            // 构建真实的文件路径
            File newFile = new File( basePath+ File.separator + fileNames);
            if (!newFile.getParentFile().exists()){
                newFile.getParentFile().mkdirs();
            }
            System.out.println(newFile.getAbsolutePath());
            file.transferTo(newFile);

        } catch (IOException e) {
            System.out.println("上传图片失败，建议手动往webapp/static下存放图片");
            e.printStackTrace();
        }
        return "http://localhost:8080/static/" + fileNames;
    }
}
